<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\BaseController;
use app\admin\middleware\Auth;
use app\common\model\Order\Order as OrderModel;
use think\facade\View;
use app\common\model\Order\Product as OrderProductModel;
use app\common\model\Express as ExpressModel;
use app\common\model\User\Record as RecordModel;

class Order extends BaseController
{
    protected $middleware = [
        Auth::class
    ];


    public function index()
    {
        $nav_title = [
            'nav_title' => '订单管理',
            'title' => '订单列表'
        ];

        // 接收查询字段
        $SearchField = $this->request->param('search_field','code');

        $keyword = $this->request->param('keyword','');

        $where = [];

        if(!empty($SearchField) && !empty($keyword))
        {
            // $where[] = [$SearchField,'like',"%$keyword%"];

            if($SearchField == 'code')
            {
                $where[] = ['code','LIKE',"%$keyword%"];
            }

        }else{
            $keyword = '请输入相应的内容';
        }

        // $OrderList = OrderProductModel::hasWhere('order',[],'*','LEFT')->where($where)->order('order.createtime','desc')->paginate(['list_rows' => 5,'query' => request()->param()]);
        $OrderList = OrderModel::with(['express','user'])->where($where)->order('createtime','desc')->paginate(['list_rows' => 5,'query' => request()->param()]);

        // 编号 currentPage 当前页 listRows 每页要显示多少条数据
        $num = ($OrderList->currentPage() - 1) * $OrderList->listRows();

        return View::fetch('',[
            'nav_title' => $nav_title,
            'OrderList' => $OrderList,
            'num' => $num,
            'SearchField' => $SearchField,
            'keyword' => $keyword
        ]);
    }


    public function info()
    {
        $nav_title = [
            'nav_title' => '订单管理',
            'title' => '订单详情'
        ];

        $orderid = $this->request->param('orderid',0);

        // 查询订单
        $Order = OrderModel::withJoin(['user','address'])->find($orderid);

        // 查询会员商品
        $VipProduct = OrderProductModel::where('orderid',$orderid)->select();

        return View::fetch('',[
            'nav_title' => $nav_title,
            'Order' => $Order,
            'VipProduct' => $VipProduct
        ]);
    }

    public function order()
    {
        if($this->request->isPost())
        {
            $orderid = $this->request->param('orderid');

            $order = OrderModel::find($orderid);

            if($order)
            {
                $this->success('查询成功',null,$order);
            }
        }
    }

    public function back()
    {
        if($this->request->isAjax())
        {
            $aciton = $this->request->param('action');

            $orderid = $this->request->param('orderid');

            // 查询数据是否存在
            $order = OrderModel::find($orderid);

            if(!$order)
            {
                $this->error('该订单不存在');
            }

            // 开启事务
            RecordModel::startTrans();
            OrderModel::startTrans();

            $record = new RecordModel();

            // 通过撤销
            if($aciton == 'success')
            {
                $OrderData = [
                    'status' => -1
                ];

                $result = $order->save($OrderData);

                if($result !== true)
                {
                    $this->error('操作失败');
                }

                $RecordData = [
                    'userid' => $order['userid'],
                    'point' => $order['price'],
                    'content' => "您的商品订单【{$order['content']}】，申请退货成功，将退款{$order['price']}元",
                    'state' => (Int)-1
                ];

                $RecordStatus = $record->save($RecordData);

                if($RecordStatus !== true)
                {
                    OrderModel::rollback();
                    $this->error('新增消费记录失败');
                }

                if($RecordStatus !== true || $result !== true)
                {
                    OrderModel::rollback();
                    RecordModel::rollback();
                    $this->error('操作失败');
                }else{
                    OrderModel::commit();
                    RecordModel::commit();
                    $this->success('同意退货');
                }


            }else{
                $OrderData = [
                    'status' => -3
                ];

                $result = $order->save($OrderData);

                if($result !== true)
                {
                    $this->error('操作失败');
                }

                $RecordData = [
                    'userid' => $order['userid'],
                    'point' => $order['price'],
                    'content' => "您的预约订单【{$order['content']}】，申请撤销失败，将联系您协商",
                    'state' => -1
                ];

                $RecordStatus = $record->save($RecordData);

                if($RecordStatus !== true)
                {
                    OrderModel::rollback();
                    $this->error('新增消费记录失败');
                }

                if($RecordStatus !== true || $result !== true)
                {
                    OrderModel::rollback();
                    RecordModel::rollback();
                    $this->error('操作失败');
                }else{
                    OrderModel::commit();
                    RecordModel::commit();
                    $this->success('拒绝退货');
                }
            }
        }
    }

    public function expre()
    {
        if($this->request->isAjax())
        {
            $ExpressData = ExpressModel::select();

            if($ExpressData)
            {
                $this->success('查询成功',null,$ExpressData);
            }else{
                $this->error('查询失败',null,$ExpressData);
            }
        }
    }


    public function express()
    {
        if($this->request->isAjax())
        {
            $express = $this->request->param('selected');

            $expcode = $this->request->param('expcode');

            $orderid = $this->request->param('orderid');

            $action = $this->request->param('action');

            $order = OrderModel::find($orderid);

            if(!$order)
            {
                $this->error('订单不存在');
            }

            // RecordModel::startTrans();
            // OrderModel::startTrans();

            $OrderData = [
                'expid' => $express,
                'expcode' => $expcode,
                'status' => 2
            ];

            $OrderStatus = $order->save($OrderData);

            if($OrderStatus !== true)
            {
                $this->error('配送信息有误');
            }else{

                if($action)
                {

                    $this->success('修改配送信息成功');
                }else{
                    $this->success('发货成功');
                    
                }
            }


        }
    }

    public function recycle()
    {
        $nav_title = [
            'nav_title' => '订单管理',
            'title' => '回收站'
        ];

        // 接收查询字段
        $SearchField = $this->request->param('search_field','code');

        $keyword = $this->request->param('keyword','');

        $where = [];

        if(!empty($SearchField) && !empty($keyword))
        {
            // $where[] = [$SearchField,'like',"%$keyword%"];

            if($SearchField == 'code')
            {
                $where[] = ['order.code','LIKE',"%$keyword%"];
            }

        }else{
            $keyword = '请输入相应的内容';
        }

        $OrderList = OrderProductModel::onlyTrashed()->withJoin('order')->where($where)->order('order.createtime','desc')->paginate(['list_rows' => 5,'query' => request()->param()]);

        // 编号 currentPage 当前页 listRows 每页要显示多少条数据
        $num = ($OrderList->currentPage() - 1) * $OrderList->listRows();

        return View::fetch('',[
            'nav_title' => $nav_title,
            'OrderList' => $OrderList,
            'num' => $num,
            'SearchField' => $SearchField,
            'keyword' => $keyword
        ]);
    }

    public function recovery()
    {
        if($this->request->isAjax())
        {
            $orderid = $this->request->param('orderid');

            if(empty($orderid))
            {
                $this->error('请选择需要恢复的订单');
            }

            // 开启事务
            OrderModel::startTrans();
            OrderProductModel::startTrans();

            if(is_array($orderid))
            {
                $OrderList = OrderModel::onlyTrashed()->whereIn('id',$orderid)->column('id');

                $OrderProductList = OrderProductModel::onlyTrashed()->whereIn('orderid',$orderid)->column('id');

                if(!$OrderList || !$OrderProductList)
                {
                    $this->error('订单不存在，无法恢复');
                }

                $OrderStatus = OrderModel::onlyTrashed()->whereIn('id',$orderid)->update(['deletetime' => null]);

                $OrderProductStatus = OrderProductModel::onlyTrashed()->whereIn('orderid',$orderid)->update(['deletetime' => null]);


                if($OrderStatus != true || $OrderProductStatus != true)
                {
                    OrderModel::rollback();
                    OrderProductModel::rollback();
                    $this->error('批量恢复失败');
                }else{
                    OrderModel::commit();
                    OrderProductModel::commit();
                    $this->success('批量恢复成功');
                }


            }else{
                $Order = OrderModel::onlyTrashed()->find($orderid);
                $OrderProduct = OrderProductModel::onlyTrashed()->where('orderid',$orderid)->find();

                if(!$Order || !$OrderProduct)
                {
                    $this->error('订单不存在，无法恢复');
                }

                $OrderStatus = $Order->restore();
                $OrderProductStatus = $OrderProduct->restore();

                if($OrderStatus !== true || $OrderProductStatus !== true)
                {
                    OrderModel::rollback();
                    OrderProductModel::rollback();
                    $this->error('恢复失败');
                }else{
                    OrderModel::commit();
                    OrderProductModel::commit();
                    $this->success('恢复成功');
                }
            }
        }
    }


    public function del()
    {
        if($this->request->isAjax())
        {
            $orderid = $this->request->param('orderid');

            $action = $this->request->param('action');

            if(empty($orderid))
            {
                $this->error('请选择需要删除的订单');
            }

            OrderModel::startTrans();
            OrderProductModel::startTrans();

            if(is_array($orderid))
            {
                if($action == 'delete')
                {
                    $OrderList = OrderModel::onlyTrashed()->whereIn('id',$orderid)->column('id');

                    $OrderProductList = OrderProductModel::onlyTrashed()->whereIn('orderid',$orderid)->column('id');
                }else{
                    $OrderList = OrderModel::whereIn('id',$orderid)->column('id');

                    $OrderProductList = OrderProductModel::whereIn('orderid',$orderid)->column('id');

                }
                
                if(!$OrderList || !$OrderProductList)
                {
                    $this->error('订单不存在，无法删除');
                }

                if($action == 'delete')
                {
                     // 软删除
                     $OrderStatus = OrderModel::destroy($orderid,true);
                     $OrderProductStatus = OrderProductModel::destroy($OrderProductList,true);
                }else{
                    // 软删除
                    $OrderStatus = OrderModel::destroy($orderid);
                    $OrderProductStatus = OrderProductModel::destroy($OrderProductList);
                }

                if($OrderStatus !== true || $OrderProductStatus !== true)
                {
                    OrderModel::rollback();
                    OrderProductModel::rollback();
                    $this->error('删除失败');
                }else{
                    OrderModel::commit();
                    OrderProductModel::commit();
                    $this->success('删除成功');
                }


            }else{
                // 单条删除
                if($action == 'delete')
                {
                    $Order = OrderModel::onlyTrashed()->find($orderid);
                    $OrderProduct = OrderProductModel::onlyTrashed()->where('orderid',$orderid)->find();

                }else{
                    // 软删除
                    $Order = OrderModel::find($orderid);

                    $OrderProduct = OrderProductModel::where('orderid',$orderid)->find();
                }
                

                if(!$Order || !$OrderProduct)
                {
                    $this->error('该订单不存在，无法删除');
                }

                if($action == 'delete')
                {
                    $OrderStatus = OrderModel::destroy($orderid,true);
                    $OrderProductStatus = OrderProductModel::destroy($OrderProduct['id'],true);
                }else{
                    // 软删除
                    $OrderStatus = OrderModel::destroy($orderid);
                    $OrderProductStatus = OrderProductModel::destroy($OrderProduct['id']);
                }

                if($OrderStatus !== true || $OrderProductStatus !== true)
                {
                    OrderModel::rollback();
                    OrderProductModel::rollback();
                    $this->error('删除失败');
                }else{
                    OrderModel::commit();
                    OrderProductModel::commit();
                    $this->success('删除成功');
                }
            }
        }
    }

    public function logistics()
    {
        $nav_title = [
            'nav_title' => '订单管理',
            'title' => '物流信息'
        ];

        $orderid = $this->request->param('orderid');

        $order = OrderModel::find($orderid);

        if(!$order)
        {
            $this->error('订单不存在');
        }

        return View::fetch('',[
            'nav_title' => $nav_title,
            'order' => $order
        ]);
    }
}
